<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Organizing code in Visual Basic</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="Visual Basic, learn Visual Basic, namespace, module, procedure, 
scope, tutorial, programming language">
<meta name="description" content="This part of the Visual Basic tutorial shows how to
organize code using modules, procedures and namespaces.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content">

<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>


<h1>Organizing code</h1>

<p>
In this part of the Visual Basic tutorial, we will show, how to organize code.
We will cover modules, procedures and namespaces and the scope. 
</p>

<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div>

<p>
Visual Basic statements are organized into blocks, modules, classes and namespaces.
This helps to make the code more maintanable and robust. Correct code organization
prevents from making errors in the code. 
</p>

<p>
The basic building blocks of a Visual Basic program are:
</p>

<ul>
<li>Assembly</li>
<li>Namespace</li>
<li>Modules</li>
<li>Classes</li>
<li>Procedures and functions</li>
<li>Blocks</li>
<li>Statements</li>
</ul>

<p>
An <b>assembly</b> is a dll or exe file. An assembly is a compiled code library for 
use in deployment, versioning and security. A <b>namespace</b> is an abstract container
providing context for the items. A <b>module</b> is a reference type available throughout 
its namespace. Classes are basic building blocks of an OOP program. A <b>procedure</b> is
a unit of a program, that is created to do a specific task. A <b>block</b> is the lowest
level organization of Visual Basic statements provided by some keywords like If or While. 
A <b>statement</b> is an atom in a Visual Basic program. Smallest unit of code. 
</p>

<p>
Closely related to this topic is the scope and duration of a variable. 
A <b>scope</b> is the visibility of the declared variable. 
</p>

<table>
<tr>
<th>Scope</th><th>Description</th>
</tr>
<tr><td>Block scope</td><td>Available only within the code block in which it is declared</td></tr>
<tr class="gray"><td>Procedure scope</td><td>Available within the procedure in which it is declared</td></tr>
<tr><td>Module scope</td><td>Available to all code within the module, class, or structure in which it is declared</td></tr>
<tr class="gray"><td>Namespace scope</td><td>Available to all code in the namespace in which it is declared</td></tr>
</table>

<p>
A <b>lifetime</b> of a variable is a period of time during which 
a variable holds a value. Local variables exists as long as the
procedure is executing. After that, they are not available anymore. 
However, if we declare a variable to be Static, the variable
continues to exist after the procedure terminates. Module,
Shared and instance variables exist for the lifetime of the 
application. 
</p>


<h2>The basic example</h2>

<p>
First, we cover some basics.
</p>

<pre class="code">
Option Strict On


Module Example

    Sub Main()
     
        Console.WriteLine("Simple example")

    End Sub
    
End Module
</pre>

<p>
In this example, we have a Module called Example. Inside the
example, we have a Main() subroutine. The statement that prints
some message to the console is placed within the Main() procedure. 
Event the most simple Visual Basic programs must be properly organized.
</p>

<pre class="code">
Option Strict On


Public Class Example

    Public Shared Sub Main()
     
        Console.WriteLine("Simple example")

    End Sub
    
End Class
</pre>

<p>
The exact example, now without the module. We can put the
code inside a class too. The Main() procedure must be declared
<code>Shared</code>, because the class is not instantiated. 
The compiler calls the Main() method without creating an instance of
the class. That is why it must be declared <code>Shared</code>. 
Java and C# work the same. 
</p>

<h2>Namespaces</h2>

<p>
Namespaces are used to organize code at the highest logical level. 
They classify and present programming elements that are exposed 
to other programs and applications. Within a namespace, we can 
declare another namespace, a class, an interface, a struct, an enum
or a delegate.
</p>

<p>
In the following code, we have two files that share the same namespace. 
</p>

<pre class="code">
Option Strict On

NameSpace ZetCode

    Module Example1
    
        Public Dim x As Integer = 0
        
        Sub Init()

            x += 100
            Console.WriteLine(x)
        
        End Sub
    
    End Module

End NameSpace
</pre>

<p>
We have a ZetCode namespace. In the namespace, we have a module
Example1. 
</p>

<pre class="explanation">
NameSpace ZetCode
</pre>

<p>
We declare a namespace called ZetCode. 
</p>

<pre class="explanation">
Public Dim x As Integer = 0
</pre>

<p>
In the module, we declare and initialize a x variable. 
</p>

<pre class="explanation">
Sub Init()
    x += 100
    Console.WriteLine(x)
End Sub
</pre>

<p>
We have an Init() method, in which we work with the
x variable. 
</p>

<pre class="code">
Option Strict On

NameSpace ZetCode

    Module Example
     
        Sub Main()
        
            Init()
            x += 100
            Console.WriteLine(x)

        End Sub
    
    End Module
              
End NameSpace
</pre>

<p>
In the second file, we work with the Init() method from 
the previous file. 
</p>

<pre class="explanation">
NameSpace ZetCode
</pre>

<p>
We work in the same namespace.
</p>

<pre class="explanation">
Init()
x += 100
Console.WriteLine(x)
</pre>

<p>
We call the Init() procedure and work with the x variable.
Both the procedure and the x variable are defined in a
different file and different module. But they are defined
in the same namespace, so we can use them. 
</p>

<pre>
$ ./samenamespace.exe 
100
200
</pre>

<p>
Output. 
</p>

<hr class="btm">

<p>
The following code example has two distinct namespaces.
We use the <code>Imports</code> keyword to import
elements from a different namespace. 
</p>

<pre class="code">
Option Strict On

NameSpace MyMath

    Public Class Basic
    
        Public Shared PI As Double = 3.141592653589
        
        Public Shared Function GetPi() As Double

            Return Me.PI
        
        End Function
    
    End Class

End NameSpace
</pre>

<p>
We have a skeleton of a Math class in a MyMath namespace.
In the Basic class, we define a PI constant and a GetPi() 
method.
</p>

<pre class="code">
Option Strict On

Imports MyMath

NameSpace ZetCode

    Public Class Example
     
        Public Shared Sub Main()

            Console.WriteLine(Basic.PI)
            Console.WriteLine(Basic.GetPi())

        End Sub
    
    End Class
              
End NameSpace
</pre>

<p>
In this file, we use the elements from the MyMath
namespace. 
</p>

<pre class="explanation">
Imports MyMath
</pre>

<p>
We import the elements from the MyMath namespace into our
namespace. 
</p>

<br>
<img src="/img/lang/vb/rootnamespace.png" alt="Root namespace">
<div class="figure">Figure: Root namespace</div>
<br>


<p>
On Visual Basic 2008 Express edition, there is a root namespace
automatically created. This can be found under project properties,
Application tab. Either delete the root namespace or include it
into the imports path. For example, if you have Testing there,
change the line to Imports Testing.MyMath. 
</p>

<pre class="explanation">
Console.WriteLine(Basic.PI)
Console.WriteLine(Basic.GetPi())
</pre>

<p>
Now we can use those elements. In our case the PI variable and
the GetPi() method.
</p>

<pre class="code">
Option Strict On

' Imports MyMath

NameSpace ZetCode

    Public Class Example
     
        Public Shared Sub Main()

            Console.WriteLine(MyMath.Basic.PI)
            Console.WriteLine(MyMath.Basic.GetPi())

        End Sub
    
    End Class
              
End NameSpace
</pre>

<p>
Note, that we do not need the <code>Imports</code> keyword.
In the example, it is commented out. We can use elements
from other namespaces by using fully qualified names of the elements. 
</p>

<h2>Modules</h2>

<p>
A module is used to organize code and wrap up variables, properties, events, and procedures
of similar use. Unlike a class, a module is not a type. A module can
be created in a namespace or in a file. A module cannot be created inside another
module, class, structure, interface or block. All members in a module
are implicitly Shared. Modules have a Friend access. This means, that a module
is accessible everywhere in an assembly. 
</p>

<pre class="code">
Option Strict On

Module First

    Public x As Byte = 11

    Public Sub FirstModule()

        Console.WriteLine("First module")

    End Sub

End Module

Module Second

    Public y As Byte = 22

    Public Sub SecondModule()

        Console.WriteLine("Second module")

    End Sub

End Module


Module Example

    Sub Main()
     
        Console.WriteLine(x)
        Console.WriteLine(Second.y)
        FirstModule()
        SecondModule()

    End Sub
    
End Module
</pre>

<p>
We have three modules defined. The first two modules have 
variables and procedures. These will be used in the third
module. 
</p>

<pre class="explanation">
Module First

    Public x As Byte = 11
...
End Module
</pre>

<p>
We can use access specifiers inside modules too. This
way we can control the accessibility of the elements
in the modules. 
</p>

<pre class="explanation">
Console.WriteLine(x)
Console.WriteLine(Second.y)
</pre>

<p>
We print the x, y variables. They are Public and
are accessible from a different module. We may use the
module name to fully specify the variable name. 
</p>

<hr class="btm">

<p>
A <b>scope</b> is a visibility of a variable. A variable with 
a module scope is available within the module, where it was declared.
</p>

<pre class="code">
Option Strict On


Module Example
 
    Private x As Integer = 0

    Sub Main()
              
        proc1()
        proc2()
        proc3()

    End Sub
    
    Sub proc1()
    
        Console.WriteLine(x)
    
    End Sub
    
    Sub proc2()
    
        x += 100
        Console.WriteLine(x)
    
    End Sub
    
    Sub proc3()
    
        x += 100
        Console.WriteLine(x)
    
    End Sub
    
End Module
</pre>

<p>
We have x variable inside the module. The variable is available
in all three procedures. 
</p>

<pre class="explanation">
Private x As Integer = 0
</pre>

<p>
This is a variable with a module scope. It is declared
outside any procedure. 
</p>

<pre class="explanation">
Sub proc2()
    x += 100
    Console.WriteLine(x)
End Sub
</pre>

<p>
Inside the proc2() procedure, we increase the x variable and 
print its contents to the console. We refere to the x variable
defined in the module. 
</p>

<pre>
$ ./modulescope.exe 
0
100
200
</pre>

<p>
Output of the example. 
</p>

<h2>Procedures</h2>

<p>
Procedures provide modularity to the code project. 
They should do only a specific task.
</p>

<pre class="code">
Option Strict On


Module Example
 
    Dim x As Integer = 0 
    
    Sub Main()
              
        Console.WriteLine(x)
        
        proc1()
        proc2()
        proc3()

    End Sub
    
    Sub proc1()
    
        Dim x As Integer 
        x += 100
    
        Console.WriteLine(x)
    
    End Sub
    
    Sub proc2()
    
        Dim x As Integer
        x += 100
        Console.WriteLine(x)
    
    End Sub
    
    Sub proc3()
    
        Dim x As Integer
        x += 100
        Console.WriteLine(x)
    
    End Sub
    
End Module
</pre>

<p>
In the preceding code example, we have three procedures beside
the main procedure. The three procedures create a local x variable 
and print it to the terminal. The main procedure refers to the
module x variable. 
</p>

<pre class="explanation">
Sub proc1()
    Dim x As Integer 
    x += 100
    Console.WriteLine(x)
End Sub
</pre>

<p>
The proc1() procedure creates a local x variable. This variable
<b>shadows</b> the one, declared at a module scope. 
</p>

<pre>
$ ./procedurescope.exe 
0
100
100
100
</pre>

<p>
The main procedure prints 0. The other procedures print 100 to the terminal.
They create their local x variables, initiate them to 0, increase by 100. 
</p>


<h2>Block scope</h2>

<p>
It is important to understand that variables declared within a block of code
like If/End If or While/End While have a limited block scope and lifetime.
The next example illustrates this.
</p>

<pre class="code">
Option Strict On


Module Example

    Sub Main()
             
        If True

            Console.WriteLine("Inside If block")        

            Dim x As Integer = 0
            Console.WriteLine(x)
            
            x += 500
            Console.WriteLine(x)

        End If

        Console.WriteLine("Outside If block")        
        
        Rem Will not compile
        Rem Console.WriteLine(x)

    End Sub
    
    
End Module
</pre>

<p>
We have an x variable declared Inside the If/End If block.
</p>

<pre class="explanation">
Rem Will not compile
Rem Console.WriteLine(x)
</pre>

<p>
The variable is not available outside the block.
If we uncomment the second line, the example will not compile. 
</p>

<p>
This part of the Visual Basic tutorial was dedicated to organizing
code. We mentioned basic organizational elements of the code like
namespaces, modules or procedures. We described variable scope
and duration, which is closely related to those elements.
</p>

<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div>
<br>


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified September 23, 2010  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

